package com.stgl.util;

import com.alibaba.fastjson.JSON;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class SecCheck {

    public static String access_token;
    /**
     *  对文本进行检测  检测是否有过敏文字
     */
    public static Map msgSecCheck(String content) {
        //access_token="34_XlYoN6RT7VB-TQ6hsQ8x4RctGr70yKu4KQ_U9JN8mjnIaeMI2gx4A1Jncbbhaz6vTvY6PUuxOuCbrlDbQwjMWnAJ0csaf3N2i9IWmIT9AWCc7MSIpIsIwgBWnQbwaTKtxhRLw-vDoCsA4hSOPRGhAHASUJ";
        if(access_token==null || access_token==""){
            getaccess_token();
        }
        String urlmsg="https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+access_token;
        Map<String, Object> mapParam = new HashMap<String, Object>();
        mapParam.put("content", content);
        String result = HttpPostUrl.wxPost(urlmsg, mapParam);
        result=HttpPostUrl.decodeUnicode(result);
        Map<String,Object>resultmap= JSON.parseObject(result);
        Map<String,Object>fmap=new HashMap<>();
        if(resultmap.get("errcode").toString().equals("0")){
            fmap.put("msg","成功");
            fmap.put("result",true);
        }else if(resultmap.get("errcode").toString().equals("87014")){
            fmap.put("msg","对不起，您填写的信息里面包含违规信息！");
            fmap.put("result",false);
        }else{
            fmap.put("msg",resultmap.get("errMsg"));
            fmap.put("result",false);
        }
        return fmap;
    }



    /**
     *  获取access_token
     */
    public static void getaccess_token() {
        ConfKit confkit= new ConfKit("wxpay.properties");
        String tappid = confkit.get("appid");
        String tappsecret = confkit.get("appsecret");
        String urlwx = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+tappid+"&secret="+tappsecret;
        String access_token_json = HttpClientUtil.sendGet(urlwx);
        Map<String, String> p_access_token = JSON.parseObject(access_token_json, HashMap.class);
        access_token=p_access_token.get("access_token");
        System.out.println(access_token);
    }


    /**
     *  对图片进行检测  检测是否违规
     */
    public static Map imgSecCheck(MultipartFile file) {
        //access_token="34_XlYoN6RT7VB-TQ6hsQ8x4RctGr70yKu4KQ_U9JN8mjnIaeMI2gx4A1Jncbbhaz6vTvY6PUuxOuCbrlDbQwjMWnAJ0csaf3N2i9IWmIT9AWCc7MSIpIsIwgBWnQbwaTKtxhRLw-vDoCsA4hSOPRGhAHASUJ";
        if(access_token==null || access_token==""){
            getaccess_token();
        }
        String urlmsg="https://api.weixin.qq.com/wxa/img_sec_check?access_token="+access_token;
        String result = uploadFile(urlmsg, file);

        Map<String,Object>resultmap= JSON.parseObject(result);
        System.out.println(resultmap);

        Map<String,Object>fmap=new HashMap<>();
        if(resultmap.get("errcode").toString().equals("87014")){
            fmap.put("msg","对不起，您提交的图片属于违规图片，请重新提交！");
            fmap.put("result",false);
        }else if(resultmap.get("errcode").toString().equals("42001")){
            access_token="";
            Map<String,Object>getmap=imgSecCheck(file);
            return getmap;
        }else{
            fmap.put("msg","上传成功");
            fmap.put("result",true);
        }
        return fmap;
    }


    /**
     * 上传二进制文件
     * @param graphurl 接口地址
     * @param file 图片文件
     * @return
     */
    public static String uploadFile(String graphurl,MultipartFile file) {
        String line = null;//接口返回的结果
        try {
            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(graphurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // 上传文件
            StringBuilder sb = new StringBuilder();
            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
                    + "https://api.weixin.qq.com" + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行，然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);

            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 读取文件数据
            out.write(file.getBytes());
            // 最后添加换行
            out.write(newLine.getBytes());

            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
                    + boundaryPrefix + newLine).getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                return line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
        }
        System.out.println(line);
        return line;
    }



    public static void main(String args[]) throws Exception {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // task to run goes here
             getaccess_token();
            }
        };
        Timer timer = new Timer();
        long delay = 0;
        long intevalPeriod = 90 * 60000;//一个半小时更新一次
        // schedules the task to be run in an interval
        timer.scheduleAtFixedRate(task, delay,
                intevalPeriod);
    }





}
